#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
事件系统
"""

import asyncio
from typing import Dict, List, Callable, Any, Optional
from enum import Enum
from common.logger import logger
from database.messsagDB import Message


class EventType(Enum):
    """事件类型枚举"""
    MESSAGE_TEXT = 1      # 文本消息
    MESSAGE_IMAGE = 3     # 图片消息
    MESSAGE_VOICE = 34    # 语音消息
    MESSAGE_VIDEO = 43    # 视频消息
    MESSAGE_EMOJI = 47    # 动画表情
    MESSAGE_MULTIMEDIA = 49  # 多媒体消息
    MESSAGE_ANY = 0       # 任意消息类型


class Event:
    """事件基类"""
    
    def __init__(self, event_type: EventType, data:Message):
        self.event_type = event_type
        self.data:[Message] = data
        self.timestamp = asyncio.get_event_loop().time()
        self.handled = False
        self.response = None
    
    def set_response(self, response: Dict[str, Any]):
        """设置响应"""
        self.response = response
        self.handled = True
    
    def is_handled(self) -> bool:
        """检查是否已处理"""
        return self.handled


class EventBus:
    """事件总线"""
    
    def __init__(self):
        self._listeners: Dict[EventType, List[Callable]] = {}
        self._async_listeners: Dict[EventType, List[Callable]] = {}
        self._middleware: List[Callable] = []
    
    def add_listener(self, event_type: EventType, handler: Callable, async_handler: bool = True):
        """添加事件监听器"""
        if async_handler:
            if event_type not in self._async_listeners:
                self._async_listeners[event_type] = []
            self._async_listeners[event_type].append(handler)
        else:
            if event_type not in self._listeners:
                self._listeners[event_type] = []
            self._listeners[event_type].append(handler)
        
        logger.debug(f"添加事件监听器: {event_type.name} -> {handler.__name__}")
    
    def remove_listener(self, event_type: EventType, handler: Callable):
        """移除事件监听器"""
        # 移除异步监听器
        if event_type in self._async_listeners:
            if handler in self._async_listeners[event_type]:
                self._async_listeners[event_type].remove(handler)
                logger.debug(f"移除异步事件监听器: {event_type.name} -> {handler.__name__}")
        
        # 移除同步监听器
        if event_type in self._listeners:
            if handler in self._listeners[event_type]:
                self._listeners[event_type].remove(handler)
                logger.debug(f"移除同步事件监听器: {event_type.name} -> {handler.__name__}")
    
    def add_middleware(self, middleware: Callable):
        """添加中间件"""
        self._middleware.append(middleware)
        logger.debug(f"添加中间件: {middleware.__name__}")
    
    async def emit(self, event: Event) -> Optional[Dict[str, Any]]:
        """发送事件"""
        try:
            # 执行中间件
            for middleware in self._middleware:
                try:
                    await middleware(event)
                except Exception as e:
                    logger.error(f"中间件执行失败: {e}")
            
            # 执行同步监听器
            if event.event_type in self._listeners:
                for handler in self._listeners[event.event_type]:
                    try:
                        result = handler(event)
                        if result and not event.is_handled():
                            event.set_response(result)
                    except Exception as e:
                        logger.error(f"同步事件处理器执行失败: {e}")
            
            # 执行异步监听器
            if event.event_type in self._async_listeners:
                for handler in self._async_listeners[event.event_type]:
                    try:
                        result = await handler(event)
                        if result and not event.is_handled():
                            event.set_response(result)
                    except Exception as e:
                        logger.error(f"异步事件处理器执行失败: {e}")
            
            # 执行任意消息类型的监听器
            if event.event_type != EventType.MESSAGE_ANY:
                await self._emit_to_any_listeners(event)
            
            return event.response
            
        except Exception as e:
            logger.error(f"事件发送失败: {e}")
            return None
    
    async def _emit_to_any_listeners(self, event: Event):
        """发送给任意消息类型的监听器"""
        # 同步监听器
        if EventType.MESSAGE_ANY in self._listeners:
            for handler in self._listeners[EventType.MESSAGE_ANY]:
                try:
                    result = handler(event)
                    if result and not event.is_handled():
                        event.set_response(result)
                except Exception as e:
                    logger.error(f"任意消息同步处理器执行失败: {e}")
        
        # 异步监听器
        if EventType.MESSAGE_ANY in self._async_listeners:
            for handler in self._async_listeners[EventType.MESSAGE_ANY]:
                try:
                    result = await handler(event)
                    if result and not event.is_handled():
                        event.set_response(result)
                except Exception as e:
                    logger.error(f"任意消息异步处理器执行失败: {e}")
    
    def get_listener_count(self, event_type: EventType) -> int:
        """获取监听器数量"""
        sync_count = len(self._listeners.get(event_type, []))
        async_count = len(self._async_listeners.get(event_type, []))
        return sync_count + async_count
    
    def clear_listeners(self, event_type: Optional[EventType] = None):
        """清除监听器"""
        if event_type:
            self._listeners.pop(event_type, None)
            self._async_listeners.pop(event_type, None)
            logger.info(f"清除事件监听器: {event_type.name}")
        else:
            self._listeners.clear()
            self._async_listeners.clear()
            logger.info("清除所有事件监听器")


# 全局事件总线实例
event_bus = EventBus()


def on_message(event_type: EventType):
    """消息事件装饰器"""
    def decorator(func):
        # 标记函数为事件处理器
        func._event_type = event_type
        func._is_event_handler = True
        return func
    return decorator


def on_any_message():
    """任意消息事件装饰器"""
    def decorator(func):
        # 标记函数为事件处理器
        func._event_type = EventType.MESSAGE_ANY
        func._is_event_handler = True
        return func
    return decorator


def middleware():
    """中间件装饰器"""
    def decorator(func):
        # 标记函数为中间件
        func._is_middleware = True
        return func
    return decorator 